import time
import random
from pipline import Pipline


def scroll_screen(browser, func):
    db_pipeline = Pipline()
    old_scroll_height = 0  # 表明页面在最上端
    get_screen_height_js = 'return document.body.scrollHeight'  # 获取页面高度的javascript语句
    scroll_js = 'window.scrollTo(0, document.body.scrollHeight)'  # 将页面下拉的Javascript语句
    new_scroll_height = browser.execute_script(get_screen_height_js)
    time.sleep(8)
    count = 0
    start_time = time.time()

    while new_scroll_height > old_scroll_height:  # 将当前页面高度与上一次的页面高度进行对比
        old_scroll_height = browser.execute_script(get_screen_height_js)  # 获取到当前页面高度
        # 空出加载的时间
        count += 1
        print("正在处理" + str(count) + "屏幕！")
        twitters = func(browser.page_source)
        db_pipeline.insert_many(twitters)
        browser.execute_script(scroll_js)  # 操控浏览器进行下拉
        ret = random.random()
        time.sleep(30 + ret * 5)#
        new_scroll_height = browser.execute_script(get_screen_height_js)
        for i in range(5):
            if new_scroll_height == old_scroll_height:
                time.sleep(10)
                new_scroll_height = browser.execute_script(get_screen_height_js)
                browser.execute_script(scroll_js)  # 操控浏览器进行下拉
            else:
                break
    end_time = time.time()
    print("运行时间：" + str(end_time - start_time))
